package com.wenbo.ocr.utils;

import com.wenbo.ocr.service.OCREngine;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

/**
 * @Author wenbo
 * @Date 2023/10/18 22:05
 **/
public class OcrUtil {

    private static final OCREngine ocrEngine = OCREngine.instance();

    public OcrUtil() {
    }

    public static String getCode(String base64) {
        byte[] bytes = Base64.getDecoder().decode(base64);
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        try {
            BufferedImage bufferedImage = ImageIO.read(bis);
            return ocrEngine.recognize(bufferedImage);
        } catch (Exception var4) {
            var4.printStackTrace();
            return null;
        }
    }

    public static String getCode(InputStream inputStream) {
        try {
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            return ocrEngine.recognize(bufferedImage);
        } catch (IOException var2) {
            var2.printStackTrace();
            return null;
        }
    }

    public static String GetCodes(String Urls, String SavaPaths) throws FileNotFoundException {
        String imageUrl = Urls;
        String savePath = SavaPaths;

        try {
            URL url = new URL(imageUrl);
            URLConnection connection = url.openConnection();
            connection.setConnectTimeout(5000);
            InputStream input = connection.getInputStream();
            byte[] data = new byte[1024];
            FileOutputStream output = new FileOutputStream(savePath);

            int len;
            while((len = input.read(data)) != -1) {
                output.write(data, 0, len);
            }

            output.close();
            input.close();
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        String code = getCode((InputStream)(new FileInputStream(SavaPaths)));
        return code;
    }
}
